import {isNull} from "@utils/stringUtil.js";

export class Users {
    userId!: number
    userName!: string
    userNameLogin!: string
    coin!: number
    mailbox!: string
    userHeadPortraitUrl!: string
    status!: string
    sex!: string
    jurisdiction!: number
    birthday!: Date
    registerTime!: Date
    userPe!: string
    userPassword!: string
    bio!: string

    static fromApiResponse(data: any): Users {
        const user = new Users()
        user.userId = data?.userId ?? -1
        user.userName = data?.userName ?? '游客'
        user.userNameLogin = data?.userNameLogin ?? '游客'
        user.coin = data?.coin ?? 0
        user.mailbox = data?.mailbox ?? ''
        user.userHeadPortraitUrl = data?.userHeadPortraitUrl ?? ''
        user.status = data?.status ?? ''
        user.sex = data?.sex ?? ''
        user.jurisdiction = data?.jurisdiction ?? 0

        function isValidDate(date: any) {
            if (date === null)
                return false
            const d = new Date(date)
            return !isNaN(d.getTime())

        }

        user.birthday = isValidDate(data?.birthday) ? new Date(data.birthday) : new Date('1970-01-01')
        user.registerTime = isValidDate(data?.registerTime) ? new Date(data.registerTime) : new Date(0)
        user.userPe = data?.userPe ?? ''
        user.userPassword = data?.userPassword ?? ''
        user.bio = data?.bio ?? ''
        return user
    }

    hasUserMsg(): boolean {
        return this.userId !== -1 && !isNull(this.userName) && !isNull(this.userNameLogin) && !isNull(this.mailbox)
    }

    toString(): string {
        return `用户名::${this.userName}\n用户邮箱:${this.mailbox}\n用户登录名:${this.userNameLogin}\n用户手机号:${this.userPe}\n用户性别:${this.sex}\n用户生日:${Users.formatDateForInput(this.birthday)}\n用户简介:${this.bio}`
    }


    static formatDateForInput(dateInMilliseconds: number | Date): string {
        if (!dateInMilliseconds) return '1970-01-01'
        const date = new Date(dateInMilliseconds)
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day}`
    }
}
